const express = require('express');
const router = express.Router();
const fs = require('fs');
const path = require('path');
const formidable = require('formidable');

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

router.post('/upload', function (req, res, next) {
  const form = new formidable.IncomingForm();
  // form.uploadDir = path.join(__dirname, '../', 'public', 'assces', 'imgs');
  form.keepExtensions = true;
  form.parse(req, (err, fields, files) => {
    let { file: { filepath, newFilename, originalFilename } } = files;
    filepath = filepath.replace('//', '\\');

    const ext = originalFilename.substring(originalFilename.lastIndexOf('.'));
    const data = fs.readFileSync(filepath, {
      encoding: "base64"
    });
    const savePath = './public/assces/imgs/' + newFilename + ext;

    // console.log(savePath);
    let file = { ...files.file };
    file.url = 'http://localhost:3000' + '/assces/imgs/' + newFilename + ext;
    fs.writeFile(savePath, data, 'base64', (err) => {
      if (err) {
        console.log("出错了", err);
        res.send(err);
      } else {
        // console.log("写入成功");
        res.send(file)
      }
    });
  })
});

module.exports = router;
